<script setup>
import {  computed,  onMounted, ref, watch} from 'vue';
import ClassItem from '@/components/ClassItem.vue';
import {  getTrainPlan } from '@/api/train';
import { ElMessage} from 'element-plus';

const MAX_OFFSET = 1;
// 课程信息
const data = ref([])

// 最早有课的时间
const earliestAvailableDate = ref('2024-08-01');


// 时间是否包含周末
const isContainsWeekend = ref(false)

const currentDateOffset = ref(0)


// 计算最早有数据
const calculateMinOffset = computed(() => {
  const earliestDate = new Date(earliestAvailableDate.value);
  const currentDate = new Date();
  const timeDiff = currentDate - earliestDate;
  const minOffset = Math.floor(timeDiff / (1000 * 60 * 60 * 24 * 7));

  return minOffset;
});


// 培训计划时间范围
const weekdaysNotWeekend = ref([
      { label: "Mon", key: "monday" },
      { label: "Tue", key: "tuesday" },
      { label: "Wed", key: "wednesday" },
      { label: "Thu", key: "thursday" },
      { label: "Fri", key: "friday" },]
);
const weekdaysHasWeekend = ref([
      { label: "Mon", key: "monday" },
      { label: "Tue", key: "tuesday" },
      { label: "Wed", key: "wednesday" },
      { label: "Thu", key: "thursday" },
      { label: "Fri", key: "friday" },
      { label: "Set", key: "saturday" },
      { label: "Sun", key: "sunday" },
    ]
);

// 当前显示的日期
const range = ref([])

const setRange = () => {
  const offset = isContainsWeekend.value ? 6 : 4;
  var date = new Date();
  // 本周一的日期


  date.setDate(date.getDate() - date.getDay() + 1 + currentDateOffset.value * 7);

  range.value[0] = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" +( date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) ;

  // 本周五的日期
  date.setDate(date.getDate() + offset);
  range.value[1] = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) ;
}

// 当前显示的日期
const rangeShow = computed(() => {
  return range.value[0] + ' ~ ' + range.value[1]
})


const spanMethod = ({ rowIndex, columnIndex }) =>  {
  const row = data.value[rowIndex];
  // 合并 companyName 相同的行
  if (columnIndex === 0) {
    let rowspan = 1;
    // 判断后续行的 companyName 是否与当前行的相同
    for (let i = rowIndex + 1; i < data.value.length; i++) {
      if (data.value[i].companyName === row.companyName) {
        rowspan++;
      } else {
        break;
      }
    }
    if (rowspan > 1) {
      // 如果有相同的 companyName，则合并这些单元格
      return { rowspan, colspan: 1 };
    } else {
      // 如果没有相同的 companyName，返回 colspan: 0 隐藏单元格
      if(rowIndex != 0 && data.value[rowIndex].companyName === data.value[rowIndex-1].companyName) {
        return { rowspan: 1, colspan: 0 };
      }
    }
  }

  // 对于其他列不做合并，默认每行每列都是独立的
  return { rowspan: 1, colspan: 1 };
}
watch(currentDateOffset,async () => {
  await getPlan()
})
// 查询函数
async function getPlan() {
  const res = await getTrainPlan(range.value[0], range.value[1], isContainsWeekend.value)
  data.value = res.trainPlan
}

onMounted(async () => {
    setRange()
    getPlan()
});



// 处理下一周
const changeWeekAdd = () => {
  if(currentDateOffset.value >= MAX_OFFSET) {
    ElMessage.warning("无法查看更多数据")
    return
  }
  currentDateOffset.value += 1;
  setRange()
}



// 处理上一周
const changeWeekSub = () => {
  if(currentDateOffset.value <= -calculateMinOffset.value) {
    ElMessage.warning("这是最早有数据的一周")
    return
  }
  currentDateOffset.value -= 1;
  setRange()
}


</script>

<template>
    <div class="home-container">
      <div class="home-systemName">
        <h3>培训计划查看</h3>
      </div>
      <div class="inp">
        <div class="left">
          <el-form-item label="时间范围" size="default">
            <el-input v-model="rangeShow"  disabled=""></el-input>
          </el-form-item>
          <el-form-item>
            <el-checkbox label="是否包含周末" name="name" size="default" v-model="isContainsWeekend"></el-checkbox>
          </el-form-item>
          <el-button type="primary" size="default" @click="changeWeekSub">上一周</el-button>
          <el-button type="primary" size="default" @click="changeWeekAdd">下一周</el-button>
        </div>
      </div>
      <el-table :data="data" style="width: 100%" size="small" :span-method="spanMethod"
      max-height="70vh"
      >
            <el-table-column header-align="center" align="center" prop="companyName" label="label" width="100px">
            </el-table-column>
            <el-table-column header-align="center" align="center" prop="groupName" label="label" width="100px">
            </el-table-column>
            <el-table-column v-for="(item)  in (isContainsWeekend ? weekdaysHasWeekend : weekdaysNotWeekend)" :key="item.key" :label="item.label"   align="center" >
              <el-table-column :prop="item.key" label="客户"  align="center"
              >
                <template #default="{row}">
                  <div style=" align-items: center" v-if="row[item.key]">
                    <ClassItem :classInfo="row[item.key]" :isOp="false" isCheck="true"
                   ></ClassItem>
                  </div>
                  <div v-else>
                    暂无课程
                  </div>
                </template>
              </el-table-column>
            </el-table-column>
      </el-table>
    </div>
</template>

<style scoped lang="less">
.home-container {
  background-color: #fff;
  padding: 20px;
}
.home-systemName {
   h3 {
    font-weight: normal
   }
}

.table-systemName-time {
    padding: 20px 0;
    text-align: center;
    border: #ebeef5 1px solid;
    border-top-left-radius: 10px;
    border-top-right-radius: 10px;
   }
   .inp {
    display: flex;
    justify-content: space-between;
    margin-top: 10px;
    .left {
      width: 50%;
      display: flex;
    }
    .el-form-item {
      margin-right: 10px;
    }
   }

   ::v-deep .el-form {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
}
::v-deep  .el-dialog .el-form-item  {
    display: block;
    width: 30%;
  }

  ::v-deep .el-dialog .el-form-item__label {
    color: black;
    font-size: 14px;
    margin-bottom: 5px;
  }
  ::v-deep .el-dialog .el-input__count {
  bottom: -15px !important;
}

</style>
